import 'package:maiji_flutter_common/entity/maiji_region.dart';
import 'package:maiji_flutter_common/network/error/maiji_flutter_http_error.dart';
import 'package:maiji_flutter_common/network/maiji_flutter_http.dart';
import 'package:maiji_flutter_common/network/maiji_flutter_network.dart';

class CommonConfig {
  static int regionId = -1;
}

class CommonConfigAPI {
  /// 获取区域参数信息
  Future<int> getRegionInfo() {
    if (CommonConfig.regionId != -1) {
      return Future.value(CommonConfig.regionId);
    }
    return NetworkClient.instance().post("common/copyright/location",
        params: {"lat": 0, "lng": 0}).then((value) {
      RegionInfo info = RegionInfo.fromJson(value);
      CommonConfig.regionId = info.userRegionID?.toInt() ?? -1;
      return CommonConfig.regionId;
    });
  }

  /// 根据视频ID和区域ID获取视频资源是否有版权
  Future<bool> getCopyrightInfo(String resId, int regionId) {
    return NetworkClient.instance().post("common/copyright/video",
        params: {"id": resId, "userRegionID": regionId}).then((value) {
      return true;
    }, onError: (error) {
      return (error is NetworkException)
          ? error.msgCd == codeCopyrightError
          : true;
    });
  }

  /// 通过视频ID获取是否拥有版权信息
  Future<bool> getCopyright(String resId) {
    return getRegionInfo()
        .then((value) => getCopyrightInfo(resId, value).then((value) {
              if (!value) {
                throw CopyrightException(msgInfo: "由于版权限制,当前资源暂时无法观看");
              }
              return true;
            }));
  }
}
